<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Many to Many - Join Table</title>
</head>
<body>
  <pre class="brush: java">
//Package declaration and imports omitted for brevity
//Post.java source
@Entity(name = "MtmUniPost")
@Table(name = "mtm_uni_post")
public class Post implements Serializable {
	
	private int id;
	private String title;
	private String text;
 	
	public Post() {}

	public Post(String title, String text) {
		this.title = title;
		this.text = text;
	}

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	private void setId(int id) {
		this.id = id;
	}

	@Column(nullable = false, length = 30)
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
	@Column(nullable = false, length = 100)
	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}
}

///////////////////////////////////////////////////

//Tag.java source
@Entity(name = "MtmUniTag")
@Table(name = "mtm_uni_Tag")
public class Tag implements Serializable {

	private int id;
	private String name;
	private Set&lt;Post&gt; posts = new HashSet&lt;Post&gt;();
	
	public Tag() {}
	
	public Tag(String name) {
		this.name = name;
	}

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	private void setId(int id) {
		this.id = id;
	}

	@Column(nullable = false, length = 30)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ManyToMany
	@JoinTable(name = "mtm_uni_post_tag",
		joinColumns = @JoinColumn(name = "tag_id"),
		inverseJoinColumns = @JoinColumn(name = "post_id")
	)
	public Set&lt;Post&gt; getPosts() {
		return posts;
	}

	private void setPosts(Set&lt;Post&gt; posts) {
		this.posts = posts;
	}
	
	public void addPost(Post post) {
		this.getPosts().add(post);
	}
	
	public void removePost(Post post) {
		this.getPosts().remove(post);
	}
}
  </pre>
</body>
</html>
